﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for hdsecurity
/// </summary>
public class security
{
    string user_id;
    string message;
    public HDDatabase hddb;
    DataTable dt_menu;
    DataTable dtPageset;
    public HDFunctions hdfu;
    static string sRedirectUrl = ConfigurationManager.AppSettings["LoginPage"]; //"Logout.aspx?EX=0"; // Modified by 'Imran Gani' 13-Mar-2013.
    bool isActiveUser = true; // Added by 'Imran Gani' 25-Nov-2013.
    bool isDBUpgrade = true; // Added by 'Imran Gani' 25-Nov-2013.

    public security()
    {
        this.hddb = new HDDatabase();
        this.hdfu = new HDFunctions();
        this.user_id = this.hdfu.getUserId();
    }
    public static string encrypt(string encryptString)
    {
        if (encryptString.Trim() == "")
            return "";
        try
        {
            return AFSecurity.Security.MaxBloxEncrypt(encryptString);
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in encrypt function. Error: " + e.Message);
            return "";
        }
    }
    public static string decrypt(string decryptString)
    {
        if (decryptString.Trim() == "")
            return "";
        try
        {
            return AFSecurity.Security.MaxBloxDecrypt(decryptString);
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in decrypt function. Error: " + e.Message);
            return "";
        }
    }
    public security(string strUserId)
    {
        this.hddb = new HDDatabase();
        this.hdfu = new HDFunctions();
        this.user_id = strUserId;
    }

    public string Message
    {
        get
        {
            return this.message;
        }
    }

    public void loadAppVariables(ref Hashtable hsAppVar)
    {
        if (HttpContext.Current.Session["company_id"] != null) hsAppVar.Add("{@current_company}", HttpContext.Current.Session["company_id"].ToString());
        if (HttpContext.Current.Session["user_afrowid"] != null) hsAppVar.Add("{@current_userafrowid}", HttpContext.Current.Session["user_afrowid"].ToString());
        if (HttpContext.Current.Session["userid"] != null) hsAppVar.Add("{@current_userid}", HttpContext.Current.Session["userid"].ToString());
        if (HttpContext.Current.Session["user_name"] != null) hsAppVar.Add("{@current_username}", HttpContext.Current.Session["user_name"].ToString());
    }

    //public void Insert_AppVariable(string Key, string Value)
    //{
    //    Key = "{@" + Key + "}";

    //    try
    //    {
    //        if (GlobalValues.hsAppVar.Contains(Key))
    //        {
    //            GlobalValues.hsAppVar[Key] = Value;
    //        }
    //        else
    //        {
    //            GlobalValues.hsAppVar.Add(Key, Value);
    //        }
    //    }
    //    catch (Exception e)
    //    {
    //        LogWriter.WriteLog("Error: " + e.Message + " in Insert_AppVariable Function");
    //    }
    //}

    public bool validate_user(string password)
    {
        string user_name = "";

        string actual_password = this.hddb.GetColumnValue("sy_usr", "password", "user_id='" + this.user_id + "'");

        if (password == actual_password)
        {
            HttpContext.Current.Session["userid"] = this.user_id.Replace("'", "''");
            HttpContext.Current.Session["user_afrowid"] = this.hddb.GetColumnValue("sy_usr", "af_row_id", "user_id='" + this.user_id + "'");
            HttpContext.Current.Session["Theme"] = this.hddb.GetColumnValue("sy_usr", "theme", "user_id='" + this.user_id + "'");
            user_name = this.hddb.GetColumnValue("sy_usr", "first_name", "user_id='" + this.user_id + "'");
            user_name = user_name + this.hddb.GetColumnValue("sy_usr", "last_name", "user_id='" + this.user_id + "'");
            HttpContext.Current.Session["user_name"] = HttpUtility.HtmlEncode(user_name);
            return true;
        }
        else
        {
            message = "Login failed, please try again";
            return false;
        }
    }
    private string getMasterField(string field, string value, string tableName, string matchfield)
    {
        try
        {
            string sql = "select " + field + " from " + tableName + " where " + matchfield + "='" + value + "'";
            HDDatabase hdd = new HDDatabase();
            DataSet ds = hdd.GetDataset(sql);
            hdd = null;
            if (ds.Tables.Count > 0)
                return ds.Tables[0].Rows[0][field].ToString();
            else
                return "";
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error " + e.Message + " in getMasterField Function");
            return "";
        }
    }
    public bool SaaSUserAuthenticate(string strCompanyId, string strUserId, string password)
    {
        bool blnSaaSUserAuthenticate = false;
        string user_name = ""; string modelConString = "";//string compConString = ""; 
        string strWhere = "company_id='" + strCompanyId.Replace("'", "''") + "' and  user_id='" + this.user_id.Replace("'", "''") + "'";

        modelConString = this.hddb.GetConnection().ConnectionString;

        DataRow dr = this.hddb.GetTableRow("ngcompanyuser", "password", strWhere);
        if (dr != null)
        {
            string actual_password = security.decrypt(dr["password"].ToString());
            if (password == actual_password)
            {
                DataTable dt = this.hddb.GetDataTable("select * from ngcompanyserver where company_id='" + strCompanyId.Replace("'", "''") + "'");
                if (dt.Rows.Count < 1) dt = this.hddb.GetDataTable("select * from ngcompanyserver where company_id='" + getMasterField("af_row_id", strCompanyId.Replace("'", "''"), "ngcompany", "company_id") + "'");
                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.Rows[0];
                    //string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + row["company_id"] + @""";Password=""" + row["company_id"] + @"_123"";Initial Catalog="""
                    //            + row["dbname"].ToString() + @"""";
                    //string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + strCompanyId + @""";Password=""" + strCompanyId + @"_123"";Initial Catalog="""
                    //           + row["dbname"].ToString() + @"""";
                    string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + strCompanyId + @""";Password=""" + strCompanyId + @"_123"";Initial Catalog="""
                                + row["dbname"].ToString() + @"""";
                    HDDatabase hdtemp = new HDDatabase(strConn);
                    if (hdtemp.isValidConnection())
                    {
                        string strTheme = "";
                        bool activestatus = true;
                        DataTable dtuser = hdtemp.GetDataTable("select * from sy_usr where user_id = '" + user_id.Replace("'", "''") + "'");
                        if (dtuser != null)
                        {
                            if (dtuser.Rows.Count > 0)
                            {
                                if (dtuser.Columns.Contains("theme"))
                                {
                                    strTheme = dtuser.Rows[0]["theme"].ToString();
                                }
                                if (dtuser.Columns.Contains("active"))
                                {
                                    activestatus = Convert2Bool(dtuser.Rows[0]["active"].ToString());
                                }
                            }
                        }
                        if (!activestatus)
                        {
                            isActiveUser = false; // Added by 'Imran Gani' 25-Nov-2013.
                            message = "Your account is inactive. Please contact your administrator";
                            return false;
                        }
                        HttpContext.Current.Session["dbcon"] = strConn;
                        HttpContext.Current.Session["userid"] = this.user_id;
                        HttpContext.Current.Session["company_id"] = strCompanyId;
                        HttpContext.Current.Session["company_afrowid"] = row["company_id"].ToString();

                        //Insert_AppVariable("current_company", strCompanyId);

                        //string strTheme = this.hddb.GetColumnValue("sy_usr", "theme", "user_id='" + this.user_id.Replace("'", "''") + "'");

                        if (strTheme == "")
                        {
                            strTheme = GlobalValues.DefaultTheme;
                        }
                        HttpContext.Current.Session["Theme"] = strTheme;
                        HttpContext.Current.Session["user_name"] = "";
                        //blnSaaSUserAuthenticate = true;
                        blnSaaSUserAuthenticate = doDBUpgrade(row["company_version"].ToString(), modelConString, strConn, row["af_row_id"].ToString());
                        isDBUpgrade = blnSaaSUserAuthenticate;
                    }
                    else
                    {
                        blnSaaSUserAuthenticate = false;
                        message = "Login failed, please try again.";
                    }
                }
                else
                {
                    blnSaaSUserAuthenticate = false;
                    message = "Login failed, please try again.";
                }
            }
            else
                message = "Login failed, please try again";
        }
        else
            message = "Login failed, please try again";

        return blnSaaSUserAuthenticate;
    }

    // Added by 'Imran Gani' on 20-Aug-2014, for SaaSUserAuthenticate without user validation
    public bool SaaSUserAuthenticateNew(string strCompanyId, string strUserId)
    {
        bool blnSaaSUserAuthenticate = false;
        string modelConString = "";//string compConString = ""; 
        modelConString = this.hddb.GetConnection().ConnectionString;
        DataTable dt = this.hddb.GetDataTable("select * from ngcompanyserver where company_id='" + strCompanyId.Replace("'", "''") + "'");
        if (dt.Rows.Count < 1) dt = this.hddb.GetDataTable("select * from ngcompanyserver where company_id='" + getMasterField("af_row_id", strCompanyId.Replace("'", "''"), "ngcompany", "company_id") + "'");
        if (dt.Rows.Count > 0)
        {
            DataRow row = dt.Rows[0];
            string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + strCompanyId + @""";Password=""" + strCompanyId + @"_123"";Initial Catalog="""
                        + row["dbname"].ToString() + @"""";
            HDDatabase hdtemp = new HDDatabase(strConn);
            if (hdtemp.isValidConnection())
            {
                string strTheme = "";
                bool activestatus = true;
                DataTable dtuser = hdtemp.GetDataTable("select * from sy_usr where user_id = '" + user_id.Replace("'", "''") + "'");
                if (dtuser != null)
                    if (dtuser.Rows.Count > 0)
                    {
                        if (dtuser.Columns.Contains("theme"))
                            strTheme = dtuser.Rows[0]["theme"].ToString();
                        if (dtuser.Columns.Contains("active"))
                            activestatus = Convert2Bool(dtuser.Rows[0]["active"].ToString());
                    }
                if (!activestatus)
                {
                    isActiveUser = false; // Added by 'Imran Gani' 25-Nov-2013.
                    message = "Your account is inactive. Please contact your administrator";
                    return false;
                }
                HttpContext.Current.Session["dbcon"] = strConn;
                HttpContext.Current.Session["userid"] = this.user_id;
                HttpContext.Current.Session["company_id"] = strCompanyId;
                HttpContext.Current.Session["company_afrowid"] = row["company_id"].ToString();

                if (strTheme == "")
                    strTheme = GlobalValues.DefaultTheme;
                HttpContext.Current.Session["Theme"] = strTheme;
                HttpContext.Current.Session["user_name"] = "";
                blnSaaSUserAuthenticate = doDBUpgrade(row["company_version"].ToString(), modelConString, strConn, row["af_row_id"].ToString());
                isDBUpgrade = blnSaaSUserAuthenticate;
            }
            else
            {
                blnSaaSUserAuthenticate = false;
                message = "Login failed, please try again.";
            }
        }
        else
        {
            blnSaaSUserAuthenticate = false;
            message = "Login failed, please try again.";
        }
        return blnSaaSUserAuthenticate;
    }
    
    private bool doDBUpgrade(string companyVersion, string modelConString, string compConString, string server_af_row_id)//implemented by sanal on 21 March 2008
    {
        SqlConnection conObj = null;
        try
        {
            string freezedVersion = "2.0.1.18"; //int freezedVersionSequence = 0;//freezed version in format #.#.#.##
            //companyVersion = "1.6.0.1";//testing
            if (companyVersion.Trim() == "")
            {
                LogWriter.WriteLog("DB Upgrade cancelled.");
                message = "Organizational data is not compatible.";
                return false;
                //return true;
            }
            string curVersion = "4.0.1.21"; //int curVersionSequence = 0; //company version in format #.#.#.##
            if (freezedVersion.ToLower().CompareTo(companyVersion.ToLower()) == 1)
            {
                LogWriter.WriteLog("DB lower than freezed version.");
                message = "Organizational data is not upgradable.";
                return false;
            }
            if (companyVersion.ToLower().CompareTo(curVersion.ToLower()) == -1)//checks for the version
            {
                DataSet dsScripts = new DataSet(); bool errorOccured = false;
                string sql = " select * from upgrade_scripts where version > '" + companyVersion + "' and version <= '" + curVersion + "' order by version asc";
                HDDatabase hdd = new HDDatabase(modelConString);
                dsScripts = hdd.GetDataset(sql);
                
                //sql = " select * from upgrade_scripts_files where version > '" + companyVersion + "' and version <= '" + curVersion + "' order by version asc";
                //DataSet dsScriptFiles = hdd.GetDataset(sql);
                hdd = null;

                if (dsScripts.Tables.Count < 0) return true;
                SqlCommand cmdObj = new SqlCommand();
                conObj = new SqlConnection(compConString);
                SqlTransaction st = null;
                int iRet = -1;//may be used later
                if (dsScripts.Tables[0].Rows.Count > 0)
                {
                    cmdObj.Connection = conObj;
                    cmdObj.Connection.Open();
                    st = conObj.BeginTransaction("DBUPGRADE");
                    cmdObj.Transaction = st;
                    foreach (DataRow dr in dsScripts.Tables[0].Rows)
                    {
                        try
                        {
                            if (dr["ddl_script"].ToString().Trim() != "")
                            {
                                cmdObj.CommandText = dr["ddl_script"].ToString();
                                iRet = cmdObj.ExecuteNonQuery();
                            }
                            if (dr["dml_script"].ToString().Trim() != "")
                            {
                                cmdObj.CommandText = dr["dml_script"].ToString();
                                iRet = cmdObj.ExecuteNonQuery();
                            }
                            if (dr["additional_script"].ToString().Trim() != "")
                            {
                                cmdObj.CommandText = dr["additional_script"].ToString();
                                iRet = cmdObj.ExecuteNonQuery();
                            }
                        }
                        catch (Exception ex)
                        {
                            errorOccured = true;
                            LogWriter.WriteLog("Error in Upgrading DB. Company version: " + companyVersion + ". Current Version: " + curVersion + ". Script file version: " + dr["version"].ToString());
                            break;
                        }
                    }
                    if (errorOccured)
                        st.Rollback("DBUPGRADE");
                    else
                        st.Commit();
                    //cmdObj.Connection.Close();
                }
                cmdObj = null; st = null; //conObj = null;

                if (!errorOccured)//update the comany with the current version since the db upgradation is success
                {
                    hdd = new HDDatabase(modelConString);
                    hdd.ExecuteCmdObj(new SqlCommand("update ngcompanyserver set company_version='" + curVersion + "' where af_row_id='" + server_af_row_id + "'"));
                    hdd = null;
                }

                if (errorOccured) message = "Organizational maintenance failed.";
                return !errorOccured;
            }
            else
                return true;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in doDBUpgrade Function: " + e.Message);
            message = "Organizational maintenance failed";
            return false;
        }
        finally
        {
            if (conObj != null)
            {
                if (conObj.State != ConnectionState.Closed)
                {
                    conObj.Close();
                }
                conObj = null;
            }
        }
    }
    //private bool upgradeFiles(string conString, ref DataSet dsFiles)
    //{
    //    bool ret= false;
    //    try
    //    {
    //        if (dsFiles == null) return ret;
    //        if (dsFiles.Tables = null) return ret;
    //        if (dsFiles.Tables.Count < 1) return ret;
    //        foreach (DataRow dr in dsFiles.Tables[0].Rows)
    //        {
    //            upgradeFile(conString, dr["file"].ToString(), dr["table_name"].ToString(), dr["column_name"].ToString(), dr["condition"].ToString());
    //        }
    //        ret = true;
    //    }
    //    catch (Exception e)
    //    {
    //        LogWriter.WriteLog("Error in upgradeFiles Function: " + e.Message);
    //    }
    //    return ret;
    //}
    //private bool upgradeFile(string compConString, string file,string tableName, string colName, string condition)
    //{

    //}
    public bool validate_menu(string strMenuId)
    {
        string strMenuRowId = this.hddb.GetColumnValue("syv_user_menu", "menu_id", "user_id='" + this.user_id + "' and menu_id='" + strMenuId + "'");

        if (strMenuRowId != "")
        {
            //log the last accessed menu by the user
            logMenuClick(strMenuId);
            return true;
        }
        else
        {
            return false;
        }

    }

    public Menu load_menu(Menu mn_main, string strMenuSql)
    {
        this.dt_menu = this.hddb.GetDataTable(strMenuSql, "Menu");
        DataTable dt_parent = new DataTable();

        dt_parent = this.dt_menu;

        //navigate through the data set and add the menu items
        int j = 0;
        string strfilter = "parent_menu_id is null or parent_menu_id = ''";
        string strsort = "menu_seq,parent_menu_id";

        foreach (DataRow row in dt_parent.Select(strfilter, strsort))
        {
            MenuItem mi_parent = new MenuItem();
            if (row["parent_menu_id"].ToString() == "")
            {
                mi_parent.Text = row["menu_name"].ToString();
                mi_parent.Value = row["af_row_id"].ToString();
                mi_parent.Selectable = true;
                if (row["pageset_id"].ToString() != "")
                {
                    mi_parent.Selectable = true;
                    mi_parent.NavigateUrl = getMenuNavigateUrl(row);
                }
                else
                {
                    mi_parent.Selectable = false;
                }
                mi_parent.ToolTip = row["menu_name"].ToString();
                mn_main.Items.AddAt(j++, mi_parent);
            }

            this.load_child_menu(mi_parent, row["af_row_id"].ToString());
        }
        return mn_main;

    }

    private string getMasterField(string field, string value, string tableName)
    {
        try
        {
            string sql = "select " + field + " from " + tableName + " where af_row_id='" + value + "'";
            HDDatabase hdd = new HDDatabase();
            DataSet ds = hdd.GetDataset(sql);
            hdd = null;
            if (ds.Tables.Count > 0)
                return ds.Tables[0].Rows[0][field].ToString();
            else
                return "";
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error " + e.Message + " in getMasterField Function");
            return "";
        }
    }

    public DataTable getMenuForUser()
    {
        DataTable dt = new DataTable("Menu");
        string sUsr_af_id = hddb.GetColumnValue("select af_row_id from sy_usr where user_id='" + this.user_id.Replace("'", "''") + "'");
        string sRol_af_id = hddb.GetColumnValue("select role_id from sy_usr_rol where user_id='" + sUsr_af_id + "'");
        //string sRol = hddb.GetColumnValue("select af_row_id from sy_rol where role_id = '" + sRol_af_id + "'");
        //dt = hddb.GetDataTable("select mnu.* from sy_mnu mnu, sy_rol_acc rol_acc where mnu.menu_id=rol_acc.menu_id and role_id='" + sRol_af_id + "' and rol_acc.is_accessible='true'", "Menu");
        if (allRightsForNGMODEL())
            dt = hddb.GetDataTable("select distinct(mnu.menu_id),  mnu.* from sy_mnu mnu, sy_rol_acc rol_acc where mnu.af_row_id=rol_acc.menu_id and role_id='" + sRol_af_id + "'", "Menu");
        else
            dt = hddb.GetDataTable("select distinct(mnu.menu_id), mnu.* from sy_mnu mnu, sy_rol_acc rol_acc where mnu.af_row_id=rol_acc.menu_id and role_id='" + sRol_af_id + "' and rol_acc.is_accessible=1 and is_active=1", "Menu");//changed by sanal on 31Jan2008 for active menus
        //if (dt.Rows.Count<1)
        //    dt = hddb.GetDataTable("select mnu.* from sy_mnu mnu, sy_rol_acc rol_acc where mnu.menu_id=rol_acc.menu_id and role_id='" + sRol_af_id + "' and rol_acc.is_accessible='true'", "Menu");
        //if (dt.Rows.Count < 1)
        //    dt = hddb.GetDataTable("select mnu.* from sy_mnu mnu, sy_rol_acc rol_acc where mnu.menu_id=rol_acc.menu_id and role_id='" + sRol_af_id + "' and rol_acc.is_accessible='true'", "Menu");
        return dt;
    }

    public Menu load_menu(Menu mn_main)
    {
        //getMenuForUser();
        //string strMenuSql = "select * from syv_user_menu where user_id='" + this.user_id.Replace("'", "''") + "'";
        //this.dt_menu = this.hddb.GetDataTable(strMenuSql, "Menu");
        this.dt_menu = getMenuForUser();
        this.dtPageset = hddb.GetDataTable("select * from sy_pgs");
        DataTable dt_parent = new DataTable();

        dt_parent = this.dt_menu;

        //navigate through the data set and add the menu items
        int j = 0;
        string strfilter = "parent_menu_id is null or parent_menu_id = ''";
        string strsort = "menu_seq,parent_menu_id";

        foreach (DataRow row in dt_parent.Select(strfilter, strsort))
        {
            MenuItem mi_parent = new MenuItem();
            if (row["parent_menu_id"].ToString() == "")
            {
                mi_parent.Text = CommonFunctions.SafeEncode(row["menu_name"].ToString());
                mi_parent.Value = row["af_row_id"].ToString();
                //mi_parent.Selectable = true;
                if (row["pageset_id"].ToString() != "" && dtPageset.Select("af_row_id='" + row["pageset_id"].ToString() + "'").Length > 0)
                {
                    mi_parent.Selectable = true;
                    mi_parent.NavigateUrl = getMenuNavigateUrl(row);
                }
                else
                {
                    mi_parent.Selectable = false;
                }
                mi_parent.ToolTip = CommonFunctions.SafeEncode(row["menu_name"].ToString());
                mn_main.Items.AddAt(j++, mi_parent);
            }

            this.load_child_menu(mi_parent, row["af_row_id"].ToString());
        }
        return mn_main;

    }

    private void load_child_menu(MenuItem mi, string parent_menu_id)
    {
        DataTable dt_child = new DataTable();
        dt_child = this.dt_menu;

        string strfilter = "isnull(parent_menu_id, '') = '" + parent_menu_id + "'";
        string strsort = "menu_seq,parent_menu_id";

        foreach (DataRow row in dt_child.Select(strfilter, strsort))
        {
            MenuItem mi_child1 = new MenuItem();
            mi_child1 = fillMenuItem(row, mi_child1, false);
            mi.ChildItems.Add(mi_child1);
            this.load_child_menu(mi_child1, row["af_row_id"].ToString());
        }
    }

    private MenuItem quickLink(DataRow dr, MenuItem MI)
    {

        MI.Text = "&nbsp;&nbsp;::&nbsp;" + dr["link_name"].ToString();
        MI.ToolTip = dr["link_name"].ToString();
        if (dr["link"] != System.DBNull.Value)
        {
            MI.Value = dr["link"].ToString();
            MI.NavigateUrl = dr["link"].ToString();
            MI.Selectable = true;
            if (Convert.ToBoolean(dr["is_new_window"].ToString()) == true)
                MI.Target = "_blank";
        }
        foreach (DataRow drChild in dr.Table.Select("af_row_id='" + dr["af_row_id"].ToString() + "'", "link_sequence"))
        {
            MenuItem miChild = new MenuItem();
            miChild.Text = "&nbsp;&nbsp;::&nbsp;" + drChild["link_name"].ToString();
            miChild.ToolTip = dr["link_name"].ToString();
            if (drChild["link"] != System.DBNull.Value)
            {
                miChild.Value = drChild["link"].ToString();
                miChild.NavigateUrl = drChild["link"].ToString();
                miChild.Selectable = true;
                if (Convert.ToBoolean(dr["is_new_window"].ToString()) == true)
                    miChild.Target = "_blank";
            }
            MI.ChildItems.Add(miChild);
        }
        //}
        return MI;
    }

    private MenuItem fillMenuItem(DataRow row, MenuItem mi_child1, bool isLastMenu)
    {
        if (!isLastMenu)
            mi_child1.Text = CommonFunctions.SafeEncode(row["menu_name"].ToString());
        else
        {
            //mi_child1.Text = "&nbsp;&nbsp;" + row["menu_name"].ToString();
            //mi_child1.Text = "&nbsp;&nbsp;<span style=\"vertical-align:bottom;\">" + row["menu_name"].ToString() + "</span>";
            // Added by srivatsan
            PageIcons icons = new PageIcons();
            string imageUrl = "";//implement by sanal on aug 28, 2009 for ff support
            try
            {
                imageUrl = icons.geticonsfrompageset(row["pageset_id"].ToString(), 1);
            }
            catch (Exception ex)
            {
                LogWriter.WriteLog("Error :fillMenuItem" + ex.Message);
                imageUrl = PageIcons.strdefaulticon.ToString();
            }
            icons = null;
            //
            mi_child1.Text = "<img border=\"0\" src=\"" + imageUrl + "\" />&nbsp;&nbsp;" + CommonFunctions.SafeEncode(row["menu_name"].ToString());//implement by sanal on aug 28, 2009 for ff support

        }
        mi_child1.ToolTip = CommonFunctions.SafeEncode(row["menu_name"].ToString());
        mi_child1.Value = row["af_row_id"].ToString();
        //if (row["pageset_id"].ToString() != "")
        //if (row["pageset_id"].ToString() != "" || (row["pageset_url_type"].ToString() == "3" && row["pageset_url"].ToString() != ""))
        if ((row["pageset_id"].ToString() != "" || (row["pageset_url_type"].ToString() == "3" && row["pageset_url"].ToString() != "") || (row["pageset_url_type"].ToString() == "2" && row["pageset_url"].ToString() != "")) && dtPageset.Select("af_row_id='" + row["pageset_id"].ToString() + "'").Length != 0)
        {
            mi_child1.Selectable = true;
            mi_child1.NavigateUrl =getMenuNavigateUrl(row);
        }
        else
        {
            mi_child1.Selectable = false;
        }

        mi_child1.ToolTip = CommonFunctions.SafeEncode(row["menu_name"].ToString());

        if (row["pageset_url_type"].ToString() == "3") //for external Url, open in new window
        {
            mi_child1.Target = "_blank";
        }
        return mi_child1;
    }

    public string getMenuNavigateUrl(DataRow row)
    {
        string strMenuNavigateUrl = "";

        string strPagesetUrlType = row["pageset_url_type"].ToString();
        string strMenuClick = row["menu_click"].ToString();
        string strPagesetUrl = "";
        string strPagesetUrlParam = "?mn=" + row["af_row_id"].ToString() + "&pgs_id=" + row["pageset_id"].ToString();

        // menu_click for acronym Id is 4
        if (strMenuClick == "1" || strMenuClick == "" || strMenuClick == "3" || strMenuClick == "4") // Modified by 'Imran Gani' on 08/05/12, to set the default Grid view.
        {
            switch (strPagesetUrlType)
            {
                case "1": // Dynamic Page
                case "2": // Static Page
                    strPagesetUrl = "DisplayGrid.aspx";
                    break;
                // commented to implement list view for static pages on 18-Oct-2007
                //case "2": // Static Page
                //    strPagesetUrl = row["pageset_url"].ToString();
                //    break;
                case "3": // External Link Page
                    strPagesetUrl = row["pageset_url"].ToString();
                    //mi_child1.Target = "_blank";
                    break;
                default:
                    strPagesetUrl = "DisplayGrid.aspx";
                    break;
            }
        }
        else if (strMenuClick == "2") // directly the navigation goes to Add new mode
        {
            switch (strPagesetUrlType)
            {
                case "1": // Dynamic Page
                    strPagesetUrl = "DynamicScreen.aspx";
                    break;
                case "2": // Static Page 
                    strPagesetUrl = row["pageset_url"].ToString();
                    break;
                case "3": // External Link Page 
                    //mi_child1.Target = "_blank";
                    break;
                default:
                    strPagesetUrl = "DynamicScreen.aspx";
                    break;

            }
        }
        else if (strMenuClick == "5") // Added by 'Imran Gani' (copied from RakaTech) on 27-May-2014, for Datasheet // directly the navigation goes to Add new mode
            strPagesetUrl = "Datasheet.aspx";

        if (strPagesetUrlType == "3") // for external link there is no parameters 
        {
            if (!strPagesetUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                strPagesetUrl = "http://" + strPagesetUrl;
            }
            strMenuNavigateUrl = strPagesetUrl;

        }
        else
        {
            strMenuNavigateUrl = strPagesetUrl + strPagesetUrlParam;
        }

        return strMenuNavigateUrl;

    }

    public bool logMenuClick(string strMenuRowId)//[Karthik]For removing duplicates on sy_las_acc_mnu table
    {
        ScreenReader sr = new ScreenReader();
        SqlCommand sc;
        bool ReturnVal = false;
        try
        {
            string af_row_id = sr.getHashKey();
            string strSql = "Insert into sy_las_acc_mnu (af_row_id,menu_id,user_id,last_accessed_date,created_by,created_at,modified_at,modified_by,owner_id) values ('" + af_row_id + "','" + strMenuRowId + "','" + this.user_id.Replace("'", "''") + "','" + DateTime.Now.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture) + "','" + HttpContext.Current.Session["user_afrowid"].ToString().Replace("'", "''") + "','" + DateTime.Now.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture) + "','" + DateTime.Now.ToUniversalTime().ToString(System.Globalization.CultureInfo.InvariantCulture) + "','" + HttpContext.Current.Session["user_afrowid"].ToString().Replace("'", "''") + "','" + HttpContext.Current.Session["user_afrowid"].ToString().Replace("'", "''") + "')";//+ ":" + DateTime.Now.Millisecond + " ms" + //string strSql = "Insert into sy_las_acc_mnu (menu_id, user_id, last_accessed_date) values ('" + strMenuRowId + "','" + this.user_id + "','" + DateTime.Now.ToString() + "')";
            sc = new SqlCommand(strSql);
            int i = this.hddb.ExecuteCmdObj(sc);

            if (i == 1)
            {
                RemoveDuplicates(af_row_id, strMenuRowId);
                ReturnVal = true;
            }
            else
            {

                ReturnVal = false;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in logMenuClick. " + e.Message);
            ReturnVal = false;
        }
        finally
        {
            sr = null;
            sc = null;
        }
        return ReturnVal;
    }

    private void RemoveDuplicates(string af_row_id, string strMenuRowId)//karthik to check is accessible
    {
        try
        {
            //Remove Duplicates
            ParameterizedThreadStart ts = new ParameterizedThreadStart(logMenuRemoveDuplicates);
            Thread tLoad = new Thread(ts);

            tLoad.IsBackground = true;
            tLoad.Priority = ThreadPriority.Lowest;
            string[] strParam = new string[] { strMenuRowId, af_row_id };
            tLoad.Start(strParam);
        }
        catch (ThreadAbortException te)
        {
            LogWriter.WriteLog("Error in RemoveDuplicates. " + te.Message);
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in RemoveDuplicates. " + e.Message);
        }
    }

    private void logMenuRemoveDuplicates(object Param)//karthik for removing duplicates in sy_las_acc_mnu object
    {
        string[] strParamArr = (string[])Param;
        string strSql = "delete top(500) from sy_las_acc_mnu where menu_id='" + strParamArr[0] + "' and user_id='" + this.user_id.Replace("'", "''") + "' and isnull(af_row_id,'')<>'" + strParamArr[1] + "'";
        SqlCommand sc = new SqlCommand(strSql);
        int i = this.hddb.ExecuteCmdObj(sc);

        sc = null;
    }
    //Uma for Recently visited 
    public DataTable getLastAccessedMenu()//karthik to check is accessible
    {
        string strMenuCnt = this.hddb.getAcrMemValue("e958a3a9b9e0fbf2", "1");
        if (strMenuCnt == "")
        {
            strMenuCnt = "5";
        }
        int itemcount = Convert.ToInt32(strMenuCnt);
        string strSql = "";
        if (allRightsForNGMODEL())
            strSql = "select distinct a.menu_seq, a.af_row_id, a.menu_id, a.menu_name, null as parent_menu_id, a.pageset_id, a.menu_click, a.pageset_url, a.pageset_url_type, b.access_date from sy_mnu a, (select top " + itemcount + " menu_id, max(last_accessed_date) access_date from sy_las_acc_mnu where user_id='" + this.user_id.Replace("'", "''") + "' group by user_id, menu_id order by access_date desc) b where a.af_row_id=b.menu_id order by access_date desc";
        else//modified by Sampath on 07-Dec-2010 for statement fix
        {
            if (HttpContext.Current.Session["roleid"] == null)
                strSql = "select distinct a.menu_seq, a.af_row_id, a.menu_id, a.menu_name, null as parent_menu_id, a.pageset_id, a.menu_click, a.pageset_url, a.pageset_url_type, b.access_date from sy_mnu a, (select top " + itemcount + " menu_id, max(last_accessed_date) access_date from sy_las_acc_mnu where user_id='" + this.user_id.Replace("'", "''") + "' group by user_id, menu_id order by access_date desc) b where a.af_row_id=b.menu_id order by access_date desc";
            if (HttpContext.Current.Session["roleid"].ToString().Trim() == "")
                strSql = "select distinct a.menu_seq, a.af_row_id, a.menu_id, a.menu_name, null as parent_menu_id, a.pageset_id, a.menu_click, a.pageset_url, a.pageset_url_type, b.access_date from sy_mnu a, (select top " + itemcount + " menu_id, max(last_accessed_date) access_date from sy_las_acc_mnu where user_id='" + this.user_id.Replace("'", "''") + "' group by user_id, menu_id order by access_date desc) b where a.af_row_id=b.menu_id order by access_date desc";
            else
                strSql = "select distinct a.menu_seq, a.af_row_id, a.menu_id, a.menu_name, null as parent_menu_id, a.pageset_id, a.menu_click, a.pageset_url, a.pageset_url_type, b.access_date from sy_mnu a, (select top " + itemcount + " menu_id, max(last_accessed_date) access_date from sy_las_acc_mnu where user_id='" + this.user_id.Replace("'", "''") + "' group by user_id, menu_id order by access_date desc) b,sy_rol_acc c where a.af_row_id=b.menu_id and a.af_row_id=c.menu_id and c.role_id='" + HttpContext.Current.Session["roleid"].ToString() + "' and a.is_active=1 and c.is_accessible=1 order by access_date desc";
        }
        return this.hddb.GetDataTable(strSql);
    }

    public DataTable getQuickLinks()
    {

        string strSql = "select * from sy_quick_links, sy_quick_link_access where sy_quick_links.af_row_id = sy_quick_link_access.quick_link and sy_quick_link_access.is_accessible='1' and role_id='" + HttpContext.Current.Session["roleid"].ToString() + "'";
        //string strSql = "select * from sy_quick_links";//"select af_row_id from sy_acr where acr_id = '29'";
        //string sAF_ROW_ID = hddb.GetColumnValue(strSql);
        //strSql = "select * from sy_acr_mem where acr_id='" + sAF_ROW_ID + "'";// and mem_id='" + strAcrMemId.Replace("'", "''") + "'";
        return hddb.GetDataTable(strSql);
    }


    public Menu loadQuickLinks(Menu mn)
    {
        DataTable dt = new DataTable();
        dt = getQuickLinks();
        int iRecent = 0;
        string strMenuCnt = this.hddb.getAcrMemValue("a5878586119ae1fa", "1");
        if (strMenuCnt == "")
        {
            strMenuCnt = "5";
        }

        if (dt != null)
        {
            if (dt.Columns.Contains("parent_link") && dt.Columns.Contains("link_sequence"))
            {
                foreach (DataRow row in dt.Select("parent_link is null", "link_sequence"))
                {
                    //DataRow[] drr = dt.Select("parent_link is null");

                    //foreach (DataRow dr in drr)
                    //{

                    MenuItem mi = new MenuItem();
                    mi = quickLink(row, mi);
                    mn.Items.Add(mi);
                    iRecent++;
                    if (iRecent.ToString() == strMenuCnt) break;
                    //}
                }
            }
        }
        return mn;
    }

    public StringBuilder loadQuickLinks()
    {
        StringBuilder sbQuickLink = new StringBuilder();
        DataTable dt = new DataTable();
        dt = getQuickLinks();
        int iRecent = 0;
        string strMenuCnt = this.hddb.getAcrMemValue("a5878586119ae1fa", "1");
        if (strMenuCnt == "")
        {
            strMenuCnt = "5";
        }

        if (dt != null)
        {
            if (dt.Columns.Contains("parent_link") && dt.Columns.Contains("link_sequence"))
            {
                foreach (DataRow row in dt.Select("parent_link is null", "link_sequence"))
                {
                    //DataRow[] drr = dt.Select("parent_link is null");

                    //foreach (DataRow dr in drr)
                    //{

                    //MenuItem mi = new MenuItem();
                    //mi = quickLink(row, mi);
                    //mn.Items.Add(mi);
                    sbQuickLink = (quickLinkNew(row, sbQuickLink));
                    iRecent++;
                    if (iRecent.ToString() == strMenuCnt) break;
                    //}
                }
                //sbQuickLink.Append("</td></tr><tr><td style='height:4px'></td></tr>");//included the first </tr>, it was missing - 18 Mar 09
            }
        }
        //if (sbQuickLink.ToString().EndsWith("<tr><td style='height:4px'></td></tr>"))//included by sanal on 18 Mar 09
        //    sbQuickLink.Remove(sbQuickLink.Length - 37, 37);
        if (sbQuickLink.Length > 0)
            //Change is made by bala for removing white space in the quick link on 22MAR2012
            sbQuickLink.Append("<table  border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width:100%\"><tr class='ChildLink'><td colspan='2' style=\"height:2px;\"></td></tr></table>");
          
        return sbQuickLink;
    }

    public Menu loadLastAccessedMenu(Menu mn)
    {
        DataTable dt = new DataTable();
        dt = getLastAccessedMenu();
        this.dtPageset = hddb.GetDataTable("select * from sy_pgs");
        int iRecent = 0;
        string strMenuCnt = this.hddb.getAcrMemValue("e958a3a9b9e0fbf2", "1");
        if (strMenuCnt == "")
        {
            strMenuCnt = "5";
        }
        foreach (DataRow row in dt.Select())
        {
            if (getRightsForMRUObjects(row["pageset_id"].ToString(), "read"))
            {
                MenuItem mi = new MenuItem();
                mi = fillMenuItem(row, mi, true);
                mn.Items.Add(mi);
                iRecent++;
                if (iRecent.ToString() == strMenuCnt) break;
            }
        }
        return mn;
    }
    // GridRowLevelSecuritySql returns SQL to append into Grid SQL
    public string GridRowLevelSecuritySql(DataTable dtaPage)
    {
        string strRowSql = "";
        string strPageID = "";
        string strTableName = "";
        foreach (DataRow row in dtaPage.Select())
        {
            strPageID = row["page_id"].ToString();
            strTableName = row["page_table_name"].ToString();

            string strRowLevelSecurityData = getRowLevelSecurityData(strPageID, strTableName);

            if (strRowLevelSecurityData != "")
            {
                strRowSql += strRowSql + " and " + strRowLevelSecurityData;
            }
        }
        return strRowSql;
    }

    public string GridRowLevelSecuritySqlForQuickSearch(DataTable dtaPage)
    {
        string strRowSql = "";
        string strTableName = "";
        foreach (DataRow row in dtaPage.Select())
        {
            strTableName = row["page_table_name"].ToString();

            string strRowLevelSecurityData = getRowLevelSecurityData(strTableName, strTableName);

            if (strRowLevelSecurityData != "")
            {
                strRowSql += strRowSql + " and " + strRowLevelSecurityData;
            }

        }
        return strRowSql;
    }

    private string RowLevelData(string TableName, string ColumnName, string ColumnValue)
    {
        string sColumnValue = "";
        try
        {
            string sSql = "Select af_row_id from sy_obj where object_table = '" + TableName.Replace("'", "''") + "'";
            string sAF_ROW_ID = hddb.GetColumnValue(sSql);
            sSql = "Select * from sy_obj_att where object_id = '" + sAF_ROW_ID + "' and attrib_id='" + ColumnName.Replace("'", "''") + "'";
            DataRow dr = hddb.GetTableRow(sSql);
            if (dr == null)
            {
                sSql = sSql = "Select * from sy_obj_mas_detail where object_id = '" + sAF_ROW_ID + "' and attrib_id='" + ColumnName.Replace("'", "''") + "'";
                dr = hddb.GetTableRow(sSql);

                if (dr != null)
                {
                    sSql = "select object_table from sy_obj where object_id = '" + dr["master_obj"].ToString().Replace("'", "''") + "'";
                    string sMasterTableName = hddb.GetColumnValue(sSql);
                    sSql = "Select af_row_id from " + sMasterTableName.Replace("'", "''") + " where " + dr["display_att"].ToString().Replace("'", "''") + "='" + ColumnValue.Replace("'", "''") + "'";
                    DataTable dtMaster = hddb.GetDataTable(sSql);
                    foreach (DataRow drMaster in dtMaster.Rows)
                        sColumnValue = sColumnValue + "'" + drMaster[0].ToString() + "',";
                }
            }
            else
            {
                //if (dr["attrib_data_type"].ToString() == "BO" || dr["attrib_data_type"].ToString() == "DA" || dr["attrib_data_type"].ToString() == "DT" || dr["attrib_data_type"].ToString() == "TX")
                sColumnValue = "'" + ColumnValue + "',";
                //else
                //sColumnValue = ColumnValue + ",";
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("RowLevelData : error : " + ex.Message);
            return "'" + ColumnValue + "',";
        }

        return sColumnValue;
    }

    public string getRowLevelSecurityData(string strPageID, string strTableName)
    {
        string strRowLevelSecurityData = "";
        string strColumnName = "";
        string strColumnValue = "";
        string strSQL = "select af_row_id from sy_acr where acr_id=9";
        strSQL = "select mem_id, mem_value1 from sy_acr_mem where acr_id='76f7313ffd0da5d6'";
        DataTable dtTypeOfData = this.hddb.GetDataTable(strSQL);
        foreach (DataRow row_dtTypeOfData in dtTypeOfData.Select(""))
        {
            strColumnName = row_dtTypeOfData["mem_value1"].ToString();
            if (this.hddb.isTableColumnExists(strTableName, strColumnName))
            {
                strSQL = "select distinct data_id from sy_usr_rol a, sy_rol_acc_dat b where a.role_id=b.role_id and a.user_id='" + hddb.GetColumnValue("select af_row_id from sy_usr where user_id='" + this.user_id + "'") + "' and type_of_data='" + row_dtTypeOfData["mem_id"] + "'";
                DataTable dtDataId = this.hddb.GetDataTable(strSQL);

                strColumnValue = "";
                foreach (DataRow row_dtDataId in dtDataId.Select())
                {
                    //strColumnValue += "'" + row_dtDataId["data_id"].ToString() + "',";
                    strColumnValue += RowLevelData(strTableName, strColumnName, row_dtDataId["data_id"].ToString());
                }
                if (strColumnValue != "")
                {
                    strColumnValue = strColumnValue.Substring(0, strColumnValue.Length - 1);
                    strRowLevelSecurityData += strPageID + "." + strColumnName + " in (" + strColumnValue + ") or ";
                }
            }
        }
        if (strRowLevelSecurityData != "")
        {
            strRowLevelSecurityData = strRowLevelSecurityData.Substring(0, strRowLevelSecurityData.Length - 4);
            strRowLevelSecurityData = " ( " + strRowLevelSecurityData + " ) ";
        }
        return strRowLevelSecurityData;
    }

    #region Object level security

    public string getServerCatalog()
    {
        string sCatalog = "afModel";
        try
        {
            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxblox.ini"))
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxblox.ini");
                string sTemp = null;
                string sBlock = null;
                do
                {
                    sTemp = sr.ReadLine();
                    if (sTemp != null)
                    {
                        if (sTemp.StartsWith("[") & sTemp.EndsWith("]"))
                            sBlock = sTemp;
                        switch (sBlock)
                        {
                            case "[SERVER]":
                                if (sTemp.IndexOf("=") != -1)
                                {
                                    switch (sTemp.Substring(0, sTemp.IndexOf("=")))
                                    {
                                        case "CATALOG":
                                            sCatalog = sTemp.Substring(sTemp.IndexOf("=") + 1);
                                            break;
                                    }
                                }
                                break;
                        }
                    }
                } while (sTemp != null);

                sr.Close();
                sr.Dispose();
                sr = null;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getServerCatalog : error : " + ex.Message);
            return "afModel";
        }
        return sCatalog;
    }

    public bool allRightsForNGMODEL()
    {
        string sServerCatalog = "afconsole";
        if (HttpContext.Current.Session["ServerCatalog"] != null)
            if (HttpContext.Current.Session["ServerCatalog"].ToString() != "")
                sServerCatalog = HttpContext.Current.Session["ServerCatalog"].ToString();

        if (sServerCatalog == "")
            sServerCatalog = getServerCatalog().ToLower();

        if (HttpContext.Current.Session["dbcon"] != null)
            if (HttpContext.Current.Session["dbcon"].ToString() != "")
                if (HttpContext.Current.Session["dbcon"].ToString().ToLower().IndexOf(sServerCatalog.ToLower()) != -1)
                    return true;
        return false;
    }

    /// <summary>
    /// Gets the value for the right as true or false for the mentioned pageset.
    /// Considers all the objects in the pageset
    /// Mostly used to display the AddNew button in the DisplayGrid
    /// </summary>
    /// <param name="strPagesetRowId"></param>
    /// <param name="Right"></param>
    /// <param name="isOr">true if the result should be an Or condition and false if the result should be an ANd condition</param>
    /// <returns>Returns true or false based on the rights of the objects</returns>
    public bool getRightsForPagesetObjects(string strPagesetRowId, string Right, bool isOr)
    {
        if (allRightsForNGMODEL()) return true;

        if (strPagesetRowId == "") return isOr;
        //string sAF_Row_ID = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_pgs", "af_row_id", "pageset_id = '" + strPagesetRowId + "'");
        //if (sAF_Row_ID == "") sAF_Row_ID = getAF_ROW_ID("sy_pgs", "pageset_id", strPagesetRowId);
        bool bReturn = !isOr;
        //string sSql = "select [object_id] from [sy_pgs_mem] where pageset_id='" + strPagesetRowId.Replace("'", "''") + "'";

        DataTable dtObjects = CommonFunctions.GetTableFromPageInfo(strPagesetRowId, "sy_pgs_mem").Copy();
        if (dtObjects == null || dtObjects.Rows.Count == 0)
            dtObjects = hddb.GetDataTable("select [object_id] from [sy_pgs_mem] where pageset_id='" + strPagesetRowId + "'");

        foreach (DataRow dr in dtObjects.Rows)
        {
            string strRights = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_obj_acc", Right, "object_id = '" + dr["object_id"].ToString().Replace("'", "''") + "'");
            if (strRights == "")
                strRights = hddb.GetColumnValue("select acc.[" + Right + "] from sy_obj_acc acc inner join sy_rol rol on rol.af_row_id=acc.role_id inner join sy_usr_rol usr_rol on usr_rol.role_id=rol.af_row_id and user_id in (select af_row_id from sy_usr where user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "') and object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'");
            if (strRights == isOr.ToString())
            {
                bReturn = isOr;
                break;
            }
        }
        return bReturn;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="strPagesetRowId"></param>
    /// <param name="read"></param>
    /// <param name="create"></param>
    /// <param name="edit"></param>
    /// <param name="delete"></param>
    public void getPagesetRights(string strPagesetRowId, ref bool read, ref bool create, ref bool edit, ref bool delete)
    {
        if (allRightsForNGMODEL())
        {
            read = true;
            create = true;
            edit = true;
            delete = true;
        }
        else
        {
            read = getRightsForPagesetObjects(strPagesetRowId, "read", true);//drMenuRights["is_read"] = HDD.getRightsForPagesetObjects(strPagesetRowId, "read", true);
            create = getRightsForPagesetObjects(strPagesetRowId, "create", false);
            edit = getRightsForPagesetObjects(strPagesetRowId, "edit", true);//drMenuRights["is_write"] = HDD.getRightsForPagesetObjects(strPagesetRowId, "edit", true);
            delete = getRightsForPagesetObjects(strPagesetRowId, "delete", false);//drMenuRights["is_remove"] = HDD.getRightsForPagesetObjects(strPagesetRowId, "delete", false);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="strPagesetRowId"></param>
    /// <param name="create"></param>
    /// <param name="edit"></param>
    /// <param name="delete"></param>
    public void getPagesetRights(string strPagesetRowId, ref bool create, ref bool edit, ref bool delete)
    {
        if (allRightsForNGMODEL())
        {
            create = true;
            edit = true;
            delete = true;
        }
        else
        {
            create = getRightsForPagesetObjects(strPagesetRowId, "create", false);
            edit = getRightsForPagesetObjects(strPagesetRowId, "edit", true);
            delete = getRightsForPagesetObjects(strPagesetRowId, "delete", false);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="Object_Id"></param>
    /// <param name="Right"></param>
    /// <returns></returns>
    public bool getObjectRightsForUser(string Object_Id, string Right)
    {
        if (allRightsForNGMODEL()) return true;

        bool bRight = false;
        string sValue = CommonFunctions.GetColValueFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), "sy_obj_acc", Right, "object_id='" + Object_Id.Replace("'", "''") + "'");
        if (sValue == "") sValue = hddb.GetColumnValue("select acc.[" + Right + "] from sy_obj_acc acc inner join sy_rol rol on rol.af_row_id=acc.role_id inner join sy_usr_rol usr_rol on usr_rol.role_id=rol.af_row_id and user_id in (select af_row_id from sy_usr where user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "') and object_id='" + Object_Id.Replace("'", "''") + "'");

        if (sValue == "")
            bRight = false;
        else
            bRight = Convert.ToBoolean(sValue);

        return bRight;
    }

    /// <summary>
    /// Get the rights for the the current menu id in the query string for the currently logged in user
    /// </summary>
    /// <returns>Datarow containing the rights</returns>
    public DataRow getMenuRightsForUser()
    {
        string sSQL = "select rol.user_id, acc.* from sy_rol_acc acc, sy_usr_rol rol where acc.role_id = rol.role_id and user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "' and menu_id='" + HttpContext.Current.Request.QueryString["mn"] + "'";
        DataRow drRights = hddb.GetTableRow(sSQL);
        return drRights;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="strPagesetRowId"></param>
    /// <param name="Right"></param>
    /// <param name="isOr"></param>
    /// <returns></returns>
    public bool getRightsForMRUObjects(string strPagesetRowId, string Right)
    {
        if (allRightsForNGMODEL()) return true;

        if (strPagesetRowId == "") return false;

        bool bReturn = false;
        //string sSql = "select [object_id] from [sy_pgs_mem] where pageset_id='" + strPagesetRowId.Replace("'", "''") + "'";
        DataTable dtObjects = CommonFunctions.GetTableFromPageInfo(strPagesetRowId, "sy_pgs_mem").Copy();
        if (dtObjects == null) dtObjects = hddb.GetDataTable("select [object_id] from [sy_pgs_mem] pgs_mem, sy_pgs pgs where pgs_mem.pageset_id=pgs.af_row_id and pgs.af_row_id='" + strPagesetRowId.Replace("'", "''") + "'");

        if (dtObjects.Rows.Count == 0) bReturn = true;// pageset that is not available

        foreach (DataRow dr in dtObjects.Rows)
        {
            //sSql = "select acc.[" + Right + "] from sy_obj_acc acc, sy_usr_rol rol where acc.role_id = rol.role_id and user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "' and object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'";
            //sSql = "select acc.[" + Right + "] from sy_obj_acc acc, sy_usr_rol rol where acc.af_row_id = rol.af_row_id and user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "' and object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'";//sSql = "select acc.[" + Right + "] from sy_obj_acc acc, sy_usr_rol rol where acc.role_id = rol.role_id and user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "' and object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'";
            string sTemp = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_obj_acc", Right, "object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'");
            //if (sTemp == "") sTemp = hddb.GetColumnValue("select acc.[" + Right + "] from sy_obj_acc acc inner join sy_rol rol on rol.af_row_id=acc.role_id inner join sy_usr_rol usr_rol on usr_rol.role_id=rol.af_row_id and user_id in (select af_row_id from sy_usr where user_id='" + HttpContext.Current.Session["userid"].ToString().Replace("'", "''") + "') and object_id='" + dr["object_id"].ToString().Replace("'", "''") + "'");
            if (sTemp == "")
            {
                bReturn = false;
                break;
            }
            else
            {
                bReturn = Convert.ToBoolean(sTemp); ;
                break;
            }
        }
        return bReturn;
    }

    #endregion

    public string setSessionExpiryURL()
    {
        string sRedirect = "";
        if (HttpContext.Current.Session["userid"] != null)
        {
            if (HttpContext.Current.Session["userid"].ToString() != "")
            {
                if (allRightsForNGMODEL()) //if (HttpContext.Current.Session["dbcon"].ToString() == "" || HttpContext.Current.Session["dbcon"].ToString().IndexOf("ngmodel") != -1)
                    sRedirectUrl = "index.aspx"; //"Logout.aspx?LG=index.aspx&EX=0";  // Modified by 'Imran Gani' 13-Mar-2013.
                else
                    sRedirectUrl = ConfigurationManager.AppSettings["LoginPage"]; //"Logout.aspx?LG=default.aspx&EX=0";  // Modified by 'Imran Gani' 13-Mar-2013, to get login page from web config
            }
            else
                sRedirect = sRedirectUrl;
        }
        else
            sRedirect = ConfigurationManager.AppSettings["LoginPage"]; //"Logout.aspx?LG=default.aspx&EX=0"; // Modified by 'Imran Gani' 13-Mar-2013, to get login page from web config
        return sRedirect;
    }

    public string SessionExpiryURL
    {
        get
        {
            return sRedirectUrl + "?continue=" + HttpUtility.UrlEncode(HttpContext.Current.Request.Url.ToString());  // Modified by 'Imran Gani' 13-Mar-2013, for continue URL of requested page.
        }
    }

    public void displayHelp(DataTable dtPage, Control ImageButton)
    {
        try
        {
            foreach (DataRow dr in dtPage.Rows)
            {
                if (dr["object_id"].ToString() != "")
                {
                    //ImageButton imgHelp = (ImageButton)ImageButton;
                    Image imgHelp = (Image)ImageButton; // Image and property added by 'Imran Gani' on 24-Apr-2013.
                    string sHelpId = CommonFunctions.GetColValueFromPageInfo((HttpContext.Current.Request.QueryString["pgs_id"] == null ? "" : HttpContext.Current.Request.QueryString["pgs_id"].ToString()), "sy_obj", "object_help_id", "object_id ='" + dr["object_id"].ToString() + "'");
                    //sHelpId = hddb.GetColumnValue("Select object_help_id from sy_obj where object_id ='" + dr["object_id"].ToString() + "'");
                    
                    if (sHelpId != "")
                    {
                        if (ConfigurationManager.AppSettings["helpURL"] != null) // Added by 'Imran Gani' on 27-Mar-2013, to get the initial URL from web.config
                            sHelpId = ConfigurationManager.AppSettings["helpURL"] + sHelpId;
                        if (Regex.IsMatch(sHelpId, "(http(s)?://)?([\\w-]+\\.)+[\\w-]+[.com]+(/[/?%&=]*)?") || sHelpId.Contains("/")) // Added by 'Imran Gani' on 14-Nov-12, for Help icon to link with url.
                            //imgHelp.OnClientClick = "window.open('" + (sHelpId.Contains("http") ? sHelpId : "https://" + sHelpId) + "');return false;";
                            imgHelp.Attributes.Add("onclick", "window.open('" + (sHelpId.Contains("http") ? sHelpId : "https://" + sHelpId) + "');return false;");
                        else
                            //code changed by Balashanugam for postback issue. return false; is added on 20-Jul-2011
                            //imgHelp.OnClientClick = "window.open('displayhelp.aspx?h_id=" + sHelpId + "',null,'toolbar=no,menubar=no,scrollbars=yes,resizable=yes,height=600,width=800,top=50,left=100');return false;";
                            imgHelp.Attributes.Add("onclick", "window.open('displayhelp.aspx?h_id=" + sHelpId + "',null,'toolbar=no,menubar=no,scrollbars=yes,resizable=yes,height=600,width=800,top=50,left=100');return false;");
                        imgHelp.Visible = true;
                        imgHelp.Attributes.Add("style", "cursor: pointer;");
                    }
                    //if (imgHelp.OnClientClick == "")
                    if(imgHelp.Attributes.Count == 0)
                        imgHelp.Visible = false;
                }
            }
        }

        catch (Exception ex)
        {
            ImageButton imgHelp = (ImageButton)ImageButton;
            imgHelp.Visible = false;
            LogWriter.WriteLog(ex.Message);
        }
    }

    public void updateUserTheme()
    {
        DataTable dt = null;
        try
        {
            string sSql = "select * from sy_usr";
            dt = hddb.GetDataTable(sSql);
            if (dt.Columns.Contains("theme"))
            {
                sSql = "update sy_usr set theme='" + HttpContext.Current.Session["theme"].ToString().Trim() + "' where user_id='" + HttpContext.Current.Session["userid"].ToString().Trim() + "'";
                SqlCommand objCommand = new SqlCommand(sSql);
                hddb.ExecuteCmdObj(objCommand);
            }
            dt.Dispose();
            dt = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog(ex.Message);
            if (dt != null)
            {
                dt.Dispose();
                dt_menu = null;
            }
        }
    }

    public string getAF_ROW_ID(string ObjectName, string UniqueField, string FieldValue)
    {
        string sSql = "Select af_row_id from [" + ObjectName.Replace("'", "''") + "] where [" + UniqueField.Replace("'", "''") + "] = '" + FieldValue.Replace("'", "''") + "'"; ;
        string sAF_ROW_ID = hddb.GetColumnValue(sSql);

        return sAF_ROW_ID;
    }
    private StringBuilder quickLinkNew(DataRow dr, StringBuilder QuickLink)//included by sanal on Aug 18, 2009 (FireFox Compatible Code)
    {
        if (dr.Table.Select("parent_link='" + dr["af_row_id"].ToString() + "'", "link_sequence").Length > 0)
        {
            string logo = "";
            QuickLink.Append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width:100%\"><tr><td colspan=\"2\" style=\"height:2px;\"></td></tr><tr style=\"cursor:pointer;\" onclick=\"javascript:ShowHideChild('" + dr["af_row_id"].ToString() + "');\" class=\"ParentLink\"><td style=\"padding-left:4px;text-align:left;\">$caption$</td><td style=\"text-align:right;padding-right:2px;\">$img$</td></tr></table>");
            QuickLink.Replace("$caption$", dr["link_name"].ToString());
            //event commented by Balashanmugam for QuickLink Image click.
            QuickLink.Replace("$img$", "<img id=\"img_" + dr["af_row_id"].ToString() + "\" style=\"cursor:pointer;\" alt='Click to collapse' src='Images/collapse3.gif'/>");//onclick=\"javascript:showHideDIV('" + dr["af_row_id"].ToString() + "');\"
            //event commented by Balashanmugam for removing empty white space only chrome and mozilla in QuickLink on 21MAR2012.
            QuickLink.Append("<table id=\"" + dr["af_row_id"].ToString() + "\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width:100%;display:block;\"><tr class='ChildLink' style=\"width:100%;\"><td colspan=\"2\" style=\"height:2px;\"></td><td></td></tr>");
            foreach (DataRow drChild in dr.Table.Select("parent_link='" + dr["af_row_id"].ToString() + "'", "link_sequence"))
            {
                QuickLink.Append("<tr class='ChildLink' style=\"height:20px;\"><td colspan=\"2\" style=\"padding-left:4px;text-align:left;\">$image$</td><td style=\"text-align:left;padding-left:2px;width:100%;vertical-align:bottom;\">$content$</td></tr>");
                //QuickLink.Append("<tr class='ChildLink' style=\"height:20px;width:100%;\"><td colspan=\"2\" style=\"padding-left:2px;text-align:left;width:100%;vertical-align:bottom;\">$image$&nbsp;&nbsp;$content$</td></tr>");
                logo = "Default.PNG";
                if (drChild["logo"].ToString() != "")
                {
                    logo = drChild["logo"].ToString();
                }
                QuickLink.Replace("$image$", "<img src=\"Images/MBIcons/Small/" + logo + "\"></img>");
                QuickLink.Replace("$content$", "&nbsp;<a class='ChildLink' href='" + drChild["link"].ToString() + "'" + (Convert.ToBoolean(drChild["is_new_window"].ToString()) == true ? " target= '_blank'" : "") + " title='" + drChild["tooltip"].ToString() + "'>" + drChild["link_name"].ToString() + "</a>");
            }
            QuickLink.Append("</table>");
            //QuickLink.Append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"width:100%\"><tr class='ChildLink'><td style=\"height:2px;\"></td></tr></table>");
        }
        return QuickLink;
    }
    #region old quicklink code - not compatible with FF
    //private StringBuilder quickLink(DataRow dr, StringBuilder QuickLink)
    //{
    //    if (dr.Table.Select("parent_link='" + dr["af_row_id"].ToString() + "'", "link_sequence").Length > 0)
    //    {
    //        QuickLink.Append("<table style='width:100%;align:center;' border='0' bordercolor='black' cellspacing='0' cellpadding='0'><tr><td style='height:2px'></td></tr><tr class='ParentLink'><td style='align:center;' valign='top'><table><tr><td width='90%' class='ParentLink'> &nbsp;");
    //        QuickLink.Append(dr["link_name"].ToString());//.Append(" <span style='font-size: 10pt; font-family: Arial'> ").Append("</span>");
    //        QuickLink.Append("</td><td width='10%'>&nbsp;<img id='img_").Append(dr["af_row_id"].ToString()).Append("' style='cursor:pointer;'");
    //        QuickLink.Append(" alt='Click to collapse' src='Images/collapse3.gif' onclick=\"javascript:showHideDIV('").Append(dr["af_row_id"].ToString()).Append("');\"  /></td></tr></table>");//
    //        QuickLink.Append("<div id='").Append(dr["af_row_id"].ToString()).Append("' style='display:block;border:solid 0px #ffffff;align:left;'><table width='100%' align='left' border='0' bordercolor='black' cellspacing='0' cellpadding='0'><tr class='ChildLink'><td></td><td style='height:2pt'></td></tr>");
    //        foreach (DataRow drChild in dr.Table.Select("parent_link='" + dr["af_row_id"].ToString() + "'", "link_sequence"))
    //        {
    //            string logo = "Default.GIF";
    //            if (drChild["logo"].ToString() != "")
    //            {
    //                logo = drChild["logo"].ToString();
    //            }

    //            QuickLink.Append("<tr class='ChildLink' style='align:left;' ><td class='ChildLink' style='width:1%;'></td><td  class='ChildLink' style='width: 99%'> <img src=Images/MBIcons/Small/"+logo+"></img> <a class='ChildLink' href='").Append(drChild["link"].ToString()).Append("'");//.Append(" <span style='font-size: 10pt; font-family: Arial'> ")
    //            if (Convert.ToBoolean(drChild["is_new_window"].ToString()) == true) QuickLink.Append("target= '_blank'");
    //            QuickLink.Append(" title='").Append(drChild["tooltip"].ToString()).Append("'>").Append(drChild["link_name"].ToString()).Append("</a></td></tr>");//</span></font><font face='arial' size='2px' color='black'>
    //        }
    //        QuickLink.Append("<tr class='ChildLink'><td></td><td style='height:2pt'></td></tr></table></div></td></tr></table>");
    //    }
    //    return QuickLink;
    //}
    #endregion
    // Commented by srivatsan
    #region
    //private StringBuilder quickLink(DataRow dr, StringBuilder QuickLink)
    //{
    //    if (dr.Table.Select("parent_link='" + dr["af_row_id"].ToString() + "'", "link_sequence").Length > 0)
    //    {
    //        QuickLink.Append("<table style='width:100%;align:center;' border='0' bordercolor='black' cellspacing='0' cellpadding='0'><tr><td style='height:2px'></td></tr><tr class='ParentLink'><td style='align:center;' valign='top'><table><tr><td width='90%' class='ParentLink'> &nbsp;");
    //        QuickLink.Append(dr["link_name"].ToString());//.Append(" <span style='font-size: 10pt; font-family: Arial'> ").Append("</span>");
    //        QuickLink.Append("</td><td width='10%'>&nbsp;<img id='img_").Append(dr["af_row_id"].ToString()).Append("' style='cursor:hand'");
    //        QuickLink.Append(" alt='Click to collapse' src='Images/collapse3.gif' onclick=\"javascript:showHideDIV('").Append(dr["af_row_id"].ToString()).Append("');\"  /></td></tr></table>");//
    //        QuickLink.Append("<div id='").Append(dr["af_row_id"].ToString()).Append("' style='display:block;border:solid 0px #ffffff;align:center;'><table width='100%' align='center' border='0' bordercolor='black' cellspacing='0' cellpadding='0'><tr class='ChildLink'><td></td><td style='height:2pt'></td></tr>");
    //        foreach (DataRow drChild in dr.Table.Select("parent_link='" + dr["af_row_id"].ToString() + "'", "link_sequence"))
    //        {
    //            QuickLink.Append("<tr class='ChildLink' style='align:center;' ><td class='ChildLink' style='width:5%;'></td><td  class='ChildLink' style='width: 95%'> &gt; <a class='ChildLink' href='").Append(drChild["link"].ToString()).Append("'");//.Append(" <span style='font-size: 10pt; font-family: Arial'> ")
    //            if (Convert.ToBoolean(drChild["is_new_window"].ToString()) == true) QuickLink.Append("target= '_blank'");
    //            QuickLink.Append(" title='").Append(drChild["tooltip"].ToString()).Append("'><font color='blue'>").Append(drChild["link_name"].ToString()).Append("</font></a></td></tr>");//</span></font><font face='arial' size='2px' color='black'>
    //        }
    //        QuickLink.Append("<tr class='ChildLink'><td></td><td style='height:2pt'></td></tr></table></div></td></tr></table>");
    //    }
    //    return QuickLink;
    //}
    #endregion

    public bool createCustomLogo(ref string fileName, ref string extension)
    {
        HDDatabase hddLogo = null;
        bool ret = false;
        try
        {
            hddLogo = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            DataTable dt = hddLogo.GetDataTable("select logo_content,logo_file_name from ngcompany where company_id='" + HttpContext.Current.Session["company_id"].ToString() + "'");
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["logo_content"] != System.DBNull.Value)
                {
                    byte[] imageData = (byte[])dt.Rows[0]["logo_content"];
                    string temp = dt.Rows[0]["logo_file_name"].ToString();
                    //fileName = fileName;//don't know why this existed at the first place.
                    temp = temp.Substring(temp.LastIndexOf("."));
                    extension = temp;
                    FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(".") + "\\Images\\CustomLogo\\" + HttpContext.Current.Session["company_afrowid"].ToString() + temp, FileMode.Create);
                    fs.Write(imageData, 0, imageData.Length);
                    fs.Flush(); fs.Close(); fs = null;
                    ret = true;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error :createCustomLogo()" + e.Message);
        }
        finally
        {
            hddLogo = null;
        }
        return ret;
    }

    public bool GetUserActiveStatus(string userid, HDDatabase HDD) // Added by srivatsan to get the active status of the user
    {
        bool status = false;

        //            status = ScreenReader.Convert2Bool(HDD.GetColumnValue("select active from ngcompanyuser where "));

        status = Convert2Bool(HDD.GetColumnValue("select active from sy_usr where user_id ='" + user_id + "'"));
        return status;
    }

    private bool Convert2Bool(string strdata)
    {
        bool result = true;
        try
        {
            if (strdata != "")
            {
                result = Convert.ToBoolean(strdata);
            }
        }
        catch (Exception ex)
        {

        }
        return result;

    }
    public void setLogo(ref Literal ltrl_logo)
    {
        //if (IsPostBack) return;//logic for transparent and large images
        ltrl_logo.Text = "<div class='backs'></div>";
        string temp = "url('images/LightBlue/logo.gif');";
        DynamicDisplayI ddi = new DynamicDisplayI();
        HDDatabase hddLogo = null;
        //security s = null;
        try
        {
            if (HttpContext.Current.Session["hasCustomLogo"] != null)//optimization to avoid the directinfo check everytime - sanal 3/2/11
            {
                if (HttpContext.Current.Session["hasCustomLogo"].ToString() == "0")
                    return;
            }
            if (HttpContext.Current.Session["company_afrowid"] != null)
            {
                DirectoryInfo di = new DirectoryInfo(HttpContext.Current.Server.MapPath(".") + "\\Images\\CustomLogo");
                FileInfo[] fis = di.GetFiles(HttpContext.Current.Session["company_afrowid"].ToString() + "*");
                if (fis.Length > 0)
                {
                    temp = "url('images/CustomLogo/" + fis[0].Name + "')";
                    //ltrl_logo.Text = "<img src='Images/CustomLogo/" + fis[0].Name + "' />";
                    ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + fis[0].Name + "');background-repeat:no-repeat;>&nbsp;</td></tr></table>";
                }
                else//if another user in the same company logs out
                {
                    if (HttpContext.Current.Session["hasCustomLogo"] != null)
                    {
                        string fName = ""; string ext = "";
                        //s = new security();
                        createCustomLogo(ref fName, ref ext);
                        ltrl_logo.Text = "<table border='0' cellpadding='0' cellspacing='0' width='236' height='76'><tr><td align=\"center\" valign=\"middle\" style=background:url('images/CustomLogo/" + HttpContext.Current.Session["company_afrowid"] + ext + "'); background-repeat:no-repeat;>&nbsp;</td></tr></table>";
                    }
                }
            }
            //HtmlTableCell htc = (HtmlTableCell)ddi.FindControl(this.Controls, "td_logo");
            //htc.Style.Add("background",temp);
        }
        catch (Exception e)
        {

        }
        finally
        {
            hddLogo = null;
            ddi = null;
            //s = null;
        }
    }

    /// <summary>
    /// This will return default dashboard associated user, if not return default dashboard from Current Role
    /// </summary>
    /// <returns></returns>
    public string GetDefaultDashboard()
    {
        HDDatabase HDD = new HDDatabase();
        string result = "";
        try
        {
            //commented and Added by Omprakash to check default dashboard for user using af_row_id. - 17 Nov 2011
            //if (HttpContext.Current.Session["userid"] != null)
            //{
                if (HttpContext.Current.Session["user_afrowid"] != null) 
                {
                    string sql = "select default_dashboard from sy_usr where af_row_id = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "'";

                    //string sql = "select default_dashboard from sy_usr where user_id = '" + HttpContext.Current.Session["userid"].ToString() + "'";
                    result = HDD.GetColumnValue(sql);
                    if (result.Trim() == "")
                    {
                        sql = "select default_dashboard From sy_rol where af_row_id = '" + HttpContext.Current.Session["roleid"].ToString() + "'";
                        result = HDD.GetColumnValue(sql);
                    }
                }
            //}
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDefaultDashboard :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }

    /// <summary>
    /// This will return Navigtation URL for the Dashboard Menu
    /// </summary>
    /// <returns></returns>
    public string GetDashboardNavigateURL(string mnuid, string strPagesetRowId)
    {
        string url = "";
        try
        {
            string defaultdashboard = GetDefaultDashboard();
            if (defaultdashboard.Trim() != "")
                url = "DashboardDesigner.aspx?pgs_id=" + strPagesetRowId + "&mn=" + mnuid + "&PK=" + defaultdashboard + "&VMODE=1&DBD=1";
            else
                url = "DisplayGrid.aspx?pgs_id=" + strPagesetRowId + "&mn=" + mnuid + "&DBD=1";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDashboardNavigateURL :" + ex.Message);
        }
        return url;
    }

    //Code added by Sampath on 15-Nov-2011 for IPP tech check - vertical privilege issue
    public bool checkRecordAccess(string af_row_id, string strPagesetRowId)
    {
        bool isAllowed = true;
        HDDatabase hdd = new HDDatabase();
        try
        {
            string tmpVar = "";
            ////displaygrid page
            //if (HttpContext.Current.Request.UrlReferrer != null)
            //{
            //    tmpVar = HttpContext.Current.Request.UrlReferrer.ToString();
            //    if (tmpVar.ToLower().IndexOf("displaygrid.aspx") > 0)
            //        return isAllowed;
            //}
            //custodian_filter
            tmpVar = "";
            //tmpVar = hdd.GetColumnValue("select custodian_filter from sy_usr where af_row_id='" + HttpContext.Current.Session["user_afrowid"].ToString() + "'");
            tmpVar = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_usr", "custodian_filter", "af_row_id='" + HttpContext.Current.Session["user_afrowid"].ToString() + "'");
            //if (tmpVar.Trim() != "mr") return isAllowed;
            //tableName
            tmpVar = "";
            tmpVar = hdd.GetColumnValue("select page_table_name from sy_pg pg, sy_pgs pgs, sy_pgs_mem mem where pg.page_id=mem.page_id and mem.pageset_id=pgs.af_row_id and pgs.af_row_id='" + strPagesetRowId + "'");
            //-----------Added by 'Imran Gani' (copied from RakaTech) on 21-June-2013 for Org Security-----------
            HDDatabase HDD = new HDDatabase();
            string str_OwnerId = "";
            string modelConString = "";
            string strpgs_id = HttpContext.Current.Request.QueryString["pgs_id"].ToString();
            modelConString = HttpContext.Current.Session["servercon"].ToString();
            if (HttpContext.Current.Session["dbcon"].ToString() != modelConString)
            {
                BusinessUnit.Access ACS = new BusinessUnit.Access(HttpContext.Current.Session["userid"].ToString(), HDD.GetConnection().ConnectionString, strPagesetRowId);
                str_OwnerId = ACS.AccessableOwners;
            }
            //----------------End for Org Security------------------
            if (tmpVar.Trim() != "")
            {
                string owner_id = hdd.GetColumnValue("select isnull(owner_id,'')[owner_id] from " + tmpVar + " where af_row_id='" + af_row_id + "'");
                if (owner_id.Trim() != "")
                {
                    if (owner_id.ToLower() != HttpContext.Current.Session["user_afrowid"].ToString().ToLower())
                    {
                        if (strPagesetRowId == "6421de320e189de8") // Added by 'Imran Gani' on 01-Feb-2013, for report security per role.
                        {
                            if (!getObjectRightsForUser(hdd.GetColumnValue("select object_id from sy_report_obj where rpt_id = '" + af_row_id + "';"), "read"))
                                isAllowed = false;
                        }
                        else if (str_OwnerId.Contains(owner_id)) //-----------Added by 'Imran Gani' (copied from RakaTech) on 21-June-2013 for Org Security-----------
                            isAllowed = true;
                        else
                            isAllowed = false;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : checkRecordAccess :" + ex.Message);
        }
        finally
        {
            hdd = null;
        }
        return isAllowed;
    }

    //Code added by Sampath on 16-Nov-2011 for IPP tech check - vertical privilege issue
    public bool checkObjectMenuAccess(string strMenuRowId)
    {
        HDDatabase hdd = new HDDatabase();
        bool isAccess = false;
        try
        {
            if (HttpContext.Current.Session["user_afrowid"] == null)//when creating company
               isAccess = true;
            else
               isAccess = Convert.ToBoolean(hdd.GetColumnValue("select acc.is_accessible from sy_rol_acc acc, sy_usr_rol rol where acc.role_id=rol.role_id and [user_id]='" + HttpContext.Current.Session["user_afrowid"].ToString() + "' and menu_id='" + strMenuRowId + "';"));
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: checkObjectMenuAccess: Error: " + ex.Message);
        }
        finally
        {
            hdd = null;
        }
        return isAccess;
    }

    /// <summary>
    /// Use to handle encoding for Js.
    /// </summary>
    /// <param name="sVal">Value to be encoded.</param>
    /// <returns>Encoded Value</returns>
    public string encodeForJs(string sVal) // Added by Imran Gani on 14-Dec-2012
    {
        try
        {
            sVal = sVal.Replace("\"", "\\\"");
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Security: encodeForJs: Error: " + ex.Message);
        }
        finally
        { }
        return sVal;
    }

    /// <summary>
    /// To handle login attempts when user provide invalid login details.
    /// </summary>
    /// <param name="strCompanyId">Company Id</param>
    /// <param name="strUserId">User Id</param>
    /// <param name="password">User Password</param>
    // Added by 'Imran Gani' on 25-Nov-2013.
    public void HandleLoginAttempts(string strCompanyId, string strUserId, string password)
    {
        DataTable dt_config = new DataTable();
        int LoginAtmpCount, userLogCount;
        try
        {
            HDDatabase HDD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            dt_config = HDD.GetDataTable("select * from [sy_acr_mem] where [acr_id] = 'de8c4e12344070c0';");
            LoginAtmpCount = Convert.ToInt32(dt_config.Select("mem_id = 'count'")[0]["mem_value1"].ToString());
            if (LoginAtmpCount == 0) return;
            userLogCount = Convert.ToInt32(HDD.GetColumnValue("select count(*) from [sy_userlog] where [client_addr] = '" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() + "' and [application] = '" + HttpContext.Current.Request.Browser.Type + "' and [created_at] > (select top 1([created_at]) from [sy_userlog] where [login_status] = 1 order by [created_at] desc);"));
            if (userLogCount == 0) return;

            DataRow[] dr_config = dt_config.Select("mem_value1 = 'enabled'");
            if (dr_config == null) return;
            switch (dr_config[0]["mem_id"].ToString())
            {
                case "block_user_account":
                    if (LoginAtmpCount > userLogCount && isActiveUser)
                    {
                        message = "Login failed. Your account will be blocked after " + (LoginAtmpCount - userLogCount).ToString() + " more attempts.";
                        return;
                    }
                    if (LoginAtmpCount <= userLogCount)
                    {
                        string strWhere = "company_id='" + strCompanyId.Replace("'", "''") + "' and  user_id='" + strUserId.Replace("'", "''") + "'";
                        DataRow dr = this.hddb.GetTableRow("ngcompanyuser", "password", strWhere);
                        if (dr != null)
                        {
                            string actual_password = security.decrypt(dr["password"].ToString());
                            if (password == actual_password) return;
                            DataTable dt = this.hddb.GetDataTable("select * from ngcompanyserver where company_id='" + strCompanyId.Replace("'", "''") + "'");
                            if (dt.Rows.Count < 1) dt = this.hddb.GetDataTable("select * from ngcompanyserver where company_id='" + getMasterField("af_row_id", strCompanyId.Replace("'", "''"), "ngcompany", "company_id") + "'");
                            if (dt.Rows.Count > 0)
                            {
                                DataRow row = dt.Rows[0];
                                string strConn = @"Data Source=""" + row["server"] + @""";User Id=""" + strCompanyId + @""";Password=""" + strCompanyId + @"_123"";Initial Catalog="""
                                            + row["dbname"].ToString() + @"""";
                                HDDatabase hdtemp = new HDDatabase(strConn);
                                if (hdtemp.isValidConnection() && LoginAtmpCount == userLogCount)
                                {
                                    hdtemp.ExecuteCmdObj(new SqlCommand("update [sy_usr] set [active] = 0 where [user_id] = '" + strUserId.Replace("'", "''") + "';"));
                                    message = "You have exceeded maximum attempts and your account has been blocked. Please contact your administrator.";
                                    return;
                                }
                            }
                        }
                        message = "Login failed. You have exceeded maximum attempts.";
                    }
                    break;

                case "delay_login_access":
                    if (LoginAtmpCount > userLogCount)
                    {
                        message = "Login failed. Your account will be disabled temporarily after " + (LoginAtmpCount - userLogCount).ToString() + " more attempts.";
                        return;
                    }
                    if (LoginAtmpCount == userLogCount)
                        message = "Login failed. You have exceeded maximum attempts, your access has been denied temporarily for " + dr_config[0]["mem_value2"].ToString() + " hours.";
                    break;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: HandleLoginAttempts: Error: " + ex.Message);
        }
        finally
        {
            dt_config.Dispose();
        }
    }

    /// <summary>
    /// To check whether user has login access which has been denied by multiple attempts.
    /// </summary>
    /// <returns>True / False</returns>
    // Added by 'Imran Gani' on 25-Nov-2013.
    public bool checkLoginAccessDelay()
    {
        DataTable dt_config = new DataTable();
        DataTable dt_usrLog = new DataTable();
        bool ret = true;
        int LoginAtmpCount;
        try
        {
            HDDatabase HDD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
            dt_config = HDD.GetDataTable("select * from [sy_acr_mem] where [acr_id] = 'de8c4e12344070c0';");
            LoginAtmpCount = Convert.ToInt32(dt_config.Select("mem_id = 'count'")[0]["mem_value1"].ToString());
            if (LoginAtmpCount == 0) return ret;
            DataRow[] dr = dt_config.Select("mem_id = 'delay_login_access' and [mem_value1] = 'enabled'");
            if (dr == null || dr.Length == 0) return ret;
            string sDelay = dr[0]["mem_value2"].ToString();
            if (sDelay == "") return ret;
            if (!isDBUpgrade) return ret;
            dt_usrLog = HDD.GetDataTable("select [created_at] from [sy_userlog] where [client_addr] = '" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString() + "' and [application] = '" + HttpContext.Current.Request.Browser.Type + "' and [created_at] > (select top 1([created_at]) from [sy_userlog] where [login_status] = 1 order by [created_at] desc) order by [created_at] desc;");
            if (dt_usrLog.Rows.Count == 0) return ret;
            if (LoginAtmpCount > dt_usrLog.Rows.Count) return ret;

            DateTime RecentLogCreatedAt = Convert.ToDateTime(dt_usrLog.Rows[0]["created_at"].ToString());
            DateTime CurrentDate = DateTime.Now.ToUniversalTime();
            TimeSpan difference = CurrentDate.Subtract(RecentLogCreatedAt);
            int TotalHours = Convert.ToInt32(difference.TotalHours);
            if (TotalHours < Convert.ToInt32(sDelay))
                return false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: checkLoginAccessDelay: Error: " + ex.Message);
        }
        finally
        {
            dt_config.Dispose();
            dt_usrLog.Dispose();
        }
        return ret;
    }

    /// <summary>
    /// To validate password length, when user trying to set / reset password.
    /// </summary>
    /// <param name="sPassword">Given new password</param>
    /// <param name="err">string to get error message if any.</param>
    /// <returns>True / False</returns>
    // Added by 'Imran Gani' on 25-Nov-2013.
    public bool validatePasswordLength(string sPassword, ref string err)
    {
        HDDatabase hdd = new HDDatabase();
        int pwdMinLength = 6, pwdMaxLength = 10; // default existing values
        string sMin, sMax;
        try
        {
            sMin = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where acr_id = '21597547e2b0fa68' and mem_id = 'minimum' and af_row_id = '91f58899abab2009' and mem_value1 = 'enabled';");
            sMax = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where acr_id = '21597547e2b0fa68' and mem_id = 'maximum' and af_row_id = '6b9dba6ffeceb242' and mem_value1 = 'enabled';");
            if (!string.IsNullOrEmpty(sMin)) pwdMinLength = Convert.ToInt32(sMin);
            if (!string.IsNullOrEmpty(sMax)) pwdMaxLength = Convert.ToInt32(sMax);
            if (sPassword.Length < pwdMinLength || sPassword.Length > pwdMaxLength)
            {
                err = "Password should be of " + pwdMinLength.ToString() + " to " + pwdMaxLength.ToString() + " characters.";
                return false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: validatePasswordLength: Error: " + ex.Message);
        }
        return true;
    }

    /// <summary>
    /// To validate Password Reuse Cycle, when user trying to change password.
    /// </summary>
    /// <param name="sPassword">Given new password</param>
    /// <param name="err">string to get error message if any.</param>
    /// <returns>True / False</returns>
    // Added by 'Imran Gani' on 25-Nov-2013.
    public bool validatePasswordReuseCycle(string sPassword, ref string err)
    {
        HDDatabase hdd = new HDDatabase();
        DataTable dt_pwdSecurityLog = new DataTable();
        string sReuse_cycle_count;
        try
        {
            sReuse_cycle_count = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where acr_id = '21597547e2b0fa68' and mem_id = 'reuse_cycle_count' and af_row_id = '4dc1c67f55dbaba9' and mem_value1 = 'enabled';");
            if (string.IsNullOrEmpty(sReuse_cycle_count) || sReuse_cycle_count == "0") return true;
            else
            {
                dt_pwdSecurityLog = hdd.GetDataTable("select top " + sReuse_cycle_count + "([password]) from [sy_password_security_log] where [applies_to] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' order by [created_at] desc;");
                foreach (DataRow dr in dt_pwdSecurityLog.Rows)
                {
                    if (security.decrypt(dr["password"].ToString()) == sPassword)
                    {
                        err = "Last " + sReuse_cycle_count + " password cannot be used. Please enter a new password.";
                        return false;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: validatePasswordLength: Error: " + ex.Message);
        }
        return true;
    }

    /// <summary>
    /// To validate the URL for its query string of pageset_id and menu_id.
    /// </summary>
    /// <param name="strError">String for Error Message.</param>
    /// <returns>True - valid URL, False - Invalid URL</returns>
    // Implemented by 'Imran Gani' on 19-Jun-2014
    public bool IsValidPageURL(ref string strError)
    {
        bool bRet = true;
        try
        {
            if (HttpContext.Current.Request.QueryString["mn"] == null || HttpContext.Current.Request.QueryString["pgs_id"] == null)
            {
                strError = "<img src=\"Images/error.gif\" alt=\"\"></img>&nbsp;Invalid page request.";
                bRet = false;
            }
            else if (HttpContext.Current.Request.QueryString["mn"].ToString() == "" || HttpContext.Current.Request.QueryString["pgs_id"].ToString() == "")
            {
                strError = "<img src=\"Images/error.gif\" alt=\"\"></img>&nbsp;Invalid page request.";
                bRet = false;
            }
            else if (!checkObjectMenuAccess(HttpContext.Current.Request.QueryString["mn"]))
            {
                strError = "<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.";
                bRet = false;
            }
            else if (HttpContext.Current.Request.QueryString["PK"] != null)
            {
                if (!checkRecordAccess(HttpContext.Current.Request.QueryString["PK"].ToString(), HttpContext.Current.Request.QueryString["pgs_id"].ToString()))
                {
                    strError = "<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.";
                    bRet = false;
                }
            }
            else
                bRet = true;
                //logMenuClick(HttpContext.Current.Request.QueryString["mn"].ToString());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Security: IsValidPageURL: Error: " + ex.Message);
        }
        return bRet;
    }
}

